package com.ruoyi.system.service;

import cn.dev33.satoken.secure.BCrypt;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.event.LogininforEvent;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.RegisterBody;
import com.ruoyi.common.core.service.DeptService;
import com.ruoyi.common.enums.UserType;
import com.ruoyi.common.exception.user.CaptchaException;
import com.ruoyi.common.exception.user.CaptchaExpireException;
import com.ruoyi.common.exception.user.UserException;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.redis.RedisUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.media.invitationCode.domain.MediaInvitationCode;
import com.ruoyi.media.invitationCode.service.IMediaInvitationCodeService;
import com.ruoyi.media.utils.WxUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.List;

/**
 * 注册校验方法
 *
 * @author Lion Li
 */
@RequiredArgsConstructor
@Service
public class SysRegisterService {

    private final ISysUserService userService;
    private final ISysConfigService configService;
    private final IMediaInvitationCodeService mediaInvitationCodeService;
    private final ISysDeptService sysDeptService;

    /**
     * 注册
     */
    public void register(RegisterBody registerBody) {
        String username = registerBody.getUsername();
        String password = registerBody.getPassword();
        String invitationCode = registerBody.getInvitationCode();

        //校验是否存在邀请码
        if (StringUtils.isEmpty(invitationCode)) {
            throw new RuntimeException("请填写邀请码注册！");
        }
        //获取邀请码
        MediaInvitationCode mediaInvitationCode =  mediaInvitationCodeService.getById(registerBody.getInvitationCode());
        if(mediaInvitationCode == null){
            throw new RuntimeException("无效的邀请码！");
        }
        //当前邀请码是否被使用
        if(mediaInvitationCode.getIsUse() == 1){
            throw new RuntimeException("该邀请码已被使用！");
        }else{
            //创建邀请码过期时间 获取毫秒时间戳
            LocalDateTime tomorrow  =  LocalDateTime.now().plusDays(Long.parseLong(mediaInvitationCode.getValidTime()));
            long endTime =  tomorrow.toInstant(ZoneOffset.of("+8")).toEpochMilli();
            //当前时间戳
            long localDate = System.currentTimeMillis();

            //添加激活时间和过期时间
            mediaInvitationCode.setActivationTime(localDate);
            mediaInvitationCode.setEndTime(endTime);
            mediaInvitationCode.setIsUse(1);
            mediaInvitationCode.setUseUserName(registerBody.getUsername());
            mediaInvitationCodeService.updateById(mediaInvitationCode);
        }

        // 校验用户类型是否存在
        String userType = UserType.getUserType(registerBody.getUserType()).getUserType();

//        boolean captchaEnabled = configService.selectCaptchaEnabled();
////         验证码开关
//        if (captchaEnabled) {
//            validateCaptcha(username, registerBody.getCode(), registerBody.getUuid(), request);
//        }
        //创建部门
        long deptId = Long.parseLong(WxUtils.getRandomNumber(16));

        long num = sysDeptService.selectNormalChildrenDeptById(Long.parseLong("100"));
        //根据用户名创建对应部门
        SysDept sysDept = new SysDept();
        sysDept.setDeptId(deptId);
        sysDept.setDeptName(username);
        sysDept.setOrderNum(Integer.parseInt(String.valueOf(num + 1)));
        sysDept.setStatus("0");
        sysDept.setParentId(Long.parseLong("100"));
        if(!sysDeptService.checkDeptNameUnique(sysDept)) {
            throw new RuntimeException("该用户名已存在！");
        }
        if(sysDeptService.insertDept(sysDept) < 1){
            throw new RuntimeException("部门创建失败！");
        }

        //创建用户
        SysUser sysUser = new SysUser();
        sysUser.setDeptId(deptId);
        sysUser.setUserName(username);
        sysUser.setNickName(username);
        sysUser.setCreateBy(username);
        sysUser.setUpdateBy(username);
        sysUser.setUserRank(1);  //所有注册用户都是主账号
        Long[] roleId = {Long.parseLong("1639625586349469697")};  //添加软件端的正常用户角色
        sysUser.setRoleIds(roleId);
        sysUser.setPassword(BCrypt.hashpw(password));
        sysUser.setUserType(userType);
        if (!userService.checkUserNameUnique(sysUser)) {
            throw new UserException("user.register.save.error", username);
        }
        int resCount = userService.insertUser(sysUser);
        if (resCount < 1) {
            throw new UserException("user.register.error");
        }

        recordLogininfor(username, Constants.REGISTER, MessageUtils.message("user.register.success"));
    }

    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid, HttpServletRequest request) {
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.defaultString(uuid, "");
        String captcha = RedisUtils.getCacheObject(verifyKey);
        RedisUtils.deleteObject(verifyKey);
        if (captcha == null) {
            recordLogininfor(username, Constants.REGISTER, MessageUtils.message("user.jcaptcha.expire"));
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha)) {
            recordLogininfor(username, Constants.REGISTER, MessageUtils.message("user.jcaptcha.error"));
            throw new CaptchaException();
        }
    }

    /**
     * 记录登录信息
     *
     * @param username 用户名
     * @param status   状态
     * @param message  消息内容
     * @return
     */
    private void recordLogininfor(String username, String status, String message) {
        LogininforEvent logininforEvent = new LogininforEvent();
        logininforEvent.setUsername(username);
        logininforEvent.setStatus(status);
        logininforEvent.setMessage(message);
        logininforEvent.setRequest(ServletUtils.getRequest());
        SpringUtils.context().publishEvent(logininforEvent);
    }

}
